package com.atgugu.flink.chapter07.state;

import com.atgugu.flink.bean.WaterSensor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @Author lzc
 * @Date 2022/4/6 10:02
 */
public class Flink04_KeyedState_Value {
    public static void main(String[] args) throws Exception {
        
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 10000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        // 当水位超过20的时候, 5s之后发出预警
        env
            .socketTextStream("hadoop162", 9999)
            .map(line -> {
                String[] data = line.split(",");
                return new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2]));
            })
            .keyBy(WaterSensor::getId)
            .process(new KeyedProcessFunction<String, WaterSensor, String>() {
                
                private ValueState<Integer> lastVcState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    // 如果要用键控状态, 必须在open中获取需要的状态类型
                    lastVcState = getRuntimeContext().getState(new ValueStateDescriptor<Integer>("lastVcState", Integer.class));
                }
                
                @Override
                public void processElement(WaterSensor value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    if (lastVcState.value() != null) {  // 判断状态中是否有值. 如果没有值, 表示第一个元素, 否则就不是第一个
                        Integer lastValue = lastVcState.value(); // 获取value状态中的值
                        
                        if (value.getVc() > 10 && lastValue > 10) {
                            out.collect(ctx.getCurrentKey() + " 连续两次水位超过10, 发出预警");
                        }
                        
                    }
                    
                    lastVcState.update(value.getVc());
                }
            })
            .print();
        
        
        env.execute("flink_timer");
        
        
    }
}
